﻿using FytSoa.Application.Cms;
using FytSoa.Application.Sys;
using FytSoa.Domain.Cms;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using FytSoa.Domain.Sys;
using FytSoa.Sugar;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.App;
[ApiExplorerSettings(GroupName = "v5")]
public class AppArticleService: IApplicationService
{
    private readonly IMapper _mapper;
    private readonly SugarRepository<CmsArticle> _thisRepository;
    public AppArticleService(IMapper mapper
    ,SugarRepository<CmsArticle> thisRepository)
    {
        _mapper = mapper;
        _thisRepository = thisRepository;
    }
    
    /// <summary>
    /// 查询文章
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CmsArticleDto>> GetArticleAsync(PageParam param)
    {
        var where = Expressionable.Create<CmsArticle>();
        where.And(m => m.Status);
        if (!string.IsNullOrEmpty (param.Key)) {
            where.And (m => m.Title.Contains (param.Key) || m.KeyWord.Contains (param.Key) || m.SubTitle.Contains (param.Key) || m.Summary.Contains (param.Key) || m.Author.Contains (param.Key) || m.Source.Contains (param.Key) || m.Tag.Equals (param.Key));
        }
        if (param.Id != 0) {
            where.And (m => m.ColumnId.ToString()!.Contains(param.Id.ToString()));
        }
        var (list,totalItems,totalPage) = await _thisRepository.GetPageResultAsync(where.ToExpression(), param.Page, param.Limit, m => m.UpdateTime);
        return new PageResult<CmsArticleDto>()
        {
            Items = _mapper.Map<List<CmsArticleDto>>(list),
            TotalItems = totalItems,
            TotalPages = totalPage
        };
    }

    /// <summary>
    /// 查询广告
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<SysAdvInfoDto>> GetAvcAsync(WhereParam param)
    {
        var where = Expressionable.Create<SysAdvInfo>();
        where.And(m => m.Status);
        if (param.Id!=0)
        {
            where.And(m => m.ColumnId == param.Id);
        }
        var advRepository = _thisRepository.ChangeRepository<SugarRepository<SysAdvInfo>>();
        var list = await advRepository.GetListAsync(where.ToExpression(), m => m.Id);
        return _mapper.Map<List<SysAdvInfoDto>>(list);
    }

    /// <summary>
    /// 查询文章详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CmsArticleDto> GetModelAsync(long id) =>
        _mapper.Map<CmsArticleDto>(await _thisRepository.GetByIdAsync(id));
}